package com.sample.wanandroidx.basic

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.sample.wanandroidx.ext.FragmentViewBindingInflater

abstract class BaseFragment<VB : ViewBinding>(private val bindingInflater: FragmentViewBindingInflater<VB>) : Fragment() {

    private var mHandler: Handler? = null

    private fun getHandler(): Handler? = mHandler

    private var _binding: VB? = null

    protected val binding: VB get() = _binding!!

    abstract fun initialization()

    /*
     * 可见的时候才执行
     */
    open fun initLazyLoad() {}

    /**
     * 在主线程中执行
     */
    open fun post(runnable: () -> Unit) = getHandler()?.post(runnable)

    /**
     * 在主线程中延时执行
     */
    open fun postDelayed(delayMilli: Long, runnable: () -> Unit) = getHandler()?.postDelayed(runnable, delayMilli)

    /**
     * 懒加载
     */
    private var isFirstLoad = true


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = bindingInflater.invoke(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mHandler = Handler(Looper.getMainLooper())
        initialization()
    }

    @CallSuper
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
        mHandler?.removeCallbacksAndMessages(null)
        mHandler = null
    }

    override fun onResume() {
        super.onResume()
        if (isFirstLoad) {
            initLazyLoad()
        }
        isFirstLoad = false
    }

}
